package com.ruoyi.web.controller.monitor;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("/monitor/env")
public class EnvController {

    // 字典：系统环境变量
    public static final String DICT_TYPE_ENV = "sys_monitor_env";

    @Autowired
    ISysDictDataService dataService;

    @Autowired
    ISysDictTypeService typeService;

    @Autowired
    Environment env;

    @RequiresPermissions("monitor:env:view")
    @GetMapping("")
    public String index() {
        return "monitor/env/index";
    }

    /**
     * 系统环境变量列表
     * @return
     */
    @RequiresPermissions("monitor:env:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list() {
        // 将环境变量的名称（key）配置在字典表中，便于管理维护
        List<SysDictData> params = dataService.selectDictDataByType(DICT_TYPE_ENV);
        params.forEach(d -> {
            d.setRemark(env.getProperty(d.getDictValue())); // remark字段存放变量的值
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(params);
        rspData.setTotal(params.size());
        return rspData;
    }

    @Log(title = "系统环境变量", businessType = BusinessType.UPDATE)
    @RequiresPermissions("monitor:env:edit")
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(String key, String val) {
        if (StrUtil.isEmpty(key) || StrUtil.isEmpty(val)) {
            return AjaxResult.error("缺少必要参数");
        }
        if (!env.containsProperty(key)) {
            return AjaxResult.error("动态参数不存在！key = " + key);
        }
        String oldVal = env.getProperty(key);
        if (isMatchBoolean(oldVal) && !isMatchBoolean(val)) {
            return AjaxResult.error("值必须是true/false");
        }
        if (issMatchInteger(oldVal) && !issMatchInteger(val)) {
            return AjaxResult.error("值必须是整数");
        }

        System.setProperty(key, val);
        log.info("update env[ {} ]: {} => {}", key, oldVal, val);

        return AjaxResult.success();
    }

    private boolean isMatchBoolean(String str) {
        return ReUtil.isMatch("^true|false$", str);
    }

    private boolean issMatchInteger(String str) {
        return ReUtil.isMatch("^-?\\d+$", str);
    }
}
